<template>
  <div class="app-container">
    <upload-excel-component
      :template-url="templateUrl"
      :on-success="handleSuccess"
    />
  </div>
</template>

<script>
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
import { excelToDate } from '@/utils/index'
import { uploadEmployee } from '@/api/employess'
export default {
  name: 'UploadExcel',
  components: { UploadExcelComponent },
  data() {
    return {
    }
  },
  computed: {
    type() {
      return this.$route.type
    },
    templateUrl() {
      if (this.type === 'employee') {
        return '/excel/员工导入模板.xlsx'
      } else {
        return '/excel/龚俊.xlsx'
      }
    }
  },
  methods: {
    async handleSuccess({ results, header }) {
      // console.log(results, header)
      if (this.type === 'employee') {
        const data = this.resolveExcelData(results)
        console.log(data)
        // 发送请求，批量添加数据
        await uploadEmployee(data)
        // console.log('-----')
      }
      // 提示消息
      this.$message.success('导入成功')
      this.$router.back()
      // 封装一个函数，用于处理数据
    },
    // 解析excel数据
    resolveExcelData(data) {
      const userRelations = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '聘用形式': 'formOfEmployment',
        '部门': 'departmentName'
      }
      return data.map(item => {
        const obj = {}
        // 遍历item
        for (const key in item) {
          // key:                  入职日期      手机号
          // userRelations[key]    timeOfEntry   mobile
          // obj[userRelations[key]] obj['timeOfEntry']
          if (key === '入职日期' || key === '转正日期') {
            obj[userRelations[key]] = excelToDate(item[key])
          } else {
            obj[userRelations[key]] = item[key]
          }
        }
        return obj
      })
    }
  }
}
</script>

<style>

</style>
